package com.isoft.airportsystem.listener;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 文件监视启动器，用于监控指定目录的文件变化
 */
@Component
public class FileRunner implements ApplicationRunner {

    private static final Logger log = org.slf4j.LoggerFactory.getLogger(FileRunner.class);
    @Value("D:\\实训项目\\file")
    private String monitorPath;

    @Value("${file.monitor.interval:1000}")
    private long interval;

    @Autowired
    private FileListener fileListener;

    @Override
    public void run(ApplicationArguments args) {
        try {
            log.info("启动文件监听服务...");
            log.info("监听目录: {}", monitorPath);
            log.info("轮询间隔: {}ms", interval);

            // 创建观察器，使用 File 对象而非路径字符串
            FileAlterationObserver observer = new FileAlterationObserver(new File(monitorPath));
            observer.addListener(fileListener);

            // 创建监视器
            FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);

            // 启动监视器
            monitor.start();
            log.info("文件监听服务启动成功");

        } catch (Exception e) {
            log.error("文件监听服务启动失败: {}", e.getMessage(), e);
            throw new RuntimeException("文件监听服务启动失败", e);
        }
    }
}